package cn.mengfly.algorithm.collection.stack;

import java.util.EmptyStackException;
import java.util.Iterator;

/**
 * 基于数组实现的栈，每次在容量满的时候进行扩容
 *
 * @author wangp
 */
public class ArrayStack<T> implements Stack<T> {

    private static final int DEFAULT_CAPACITY = 16;
    private Object[] ts;
    private int size;
    private final int capacity;

    public ArrayStack(int capacity) {
        if (capacity <= 0) {
            capacity = DEFAULT_CAPACITY;
        }

        ts = new Object[capacity];
        this.capacity = capacity;
    }


    public ArrayStack() {
        this(DEFAULT_CAPACITY);
    }


    @Override
    public void push(T t) {
        if (size == ts.length) {
            resize(2 * ts.length);
        }
        ts[size++] = t;
    }

    private void resize(int resize) {
        Object[] newTs = new Object[resize];
        System.arraycopy(ts, 0, newTs, 0, size);
        ts = newTs;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T peak() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return (T) ts[(size - 1)];
    }

    @SuppressWarnings("unchecked")
    @Override
    public T pop() {
        if (isEmpty()) {
            return null;
        }
        final T t = (T) ts[--size];

        // 避免对象游离
        ts[size] = null;

        if (size > capacity && size < ts.length / 4) {
            resize(ts.length / 2);
        }

        return t;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++) {
            ts[i] = null;
        }
        size = 0;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            final Object[] elementsOfCopy = ts;

            int curIndex = 0;
            final int maxSize = size;

            @Override
            public boolean hasNext() {
                return curIndex < maxSize;
            }

            @Override
            public T next() {
                //noinspection unchecked
                return (T) elementsOfCopy[curIndex++];
            }
        };
    }
}
